package com.wanmait.baohan.controller;

import com.wanmait.baohan.util.JSONResult;
import com.wanmait.baohan.util.TimestampEditor;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
@ControllerAdvice
public class CommonAdviceController {
    /**如果是请求json出现异常，直接返回异常信息
     * 如果是其他异常，跳转到error页面
     * */
    @ExceptionHandler(Exception.class)
    public Object processException(Exception e, HttpServletRequest request) {
        if(isAjax(request)) {
            return JSONResult.errorException(e.getMessage());
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("exception",e);
        modelAndView.addObject("url",request.getRequestURL());
        modelAndView.setViewName("error");
        return modelAndView;
    }

    /**如果请求json，返回true*/
    public boolean isAjax(HttpServletRequest request) {
        return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
    }

    @InitBinder
    public void initBinder(WebDataBinder dataBinder)
    {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dataBinder.registerCustomEditor(Date.class,new CustomDateEditor(dateFormat,true));
        dataBinder.registerCustomEditor(Timestamp.class,new TimestampEditor("yyyy-MM-dd"));
    }


}
